<?php
// +----------------------------------------------------------------------+
// | The Answern Inc                                                  |
// +----------------------------------------------------------------------+
// | Copyright (c) 2017, Answern Inc. All rights reserved.            |
// +----------------------------------------------------------------------+
// | Authors: Answern Inc. 
// |                                                                      |
// +----------------------------------------------------------------------+
 

namespace App\Controllers\Common;
use \App\Libs\Base\Constant;
use App\Models\User\User;

class SetPhone extends \App\Libs\Base\BaseAction
{
	 protected function beforeRun() {
         parent::beforeRun();
         $this->needLogin = TRUE;
     }
	public function execute() {
		$user = $this->session->user;

		//手机号登录
		$phone = $this->request->get('phone');//手机号
		$captcha = $this->request->get('captcha');//验证码
	
		
		if( empty( $phone ) ){
			return \App\Libs\Views\Json::view(1, '手机号不能为空', null);
		}
		if( empty( $captcha ) ){
			return \App\Libs\Views\Json::view(1, '验证码不能为空', null);
		}
		if ($user->loginCaptcha($captcha)) {
			//验证手机号是否存在
			if( $user->phone == $phone ){
				return \App\Libs\Views\Json::view(1, '原手机号与新手机号相同', null);	
			}
			$findUserOne = $user->findOne(array(
				' phone = :phone:',
				'bind' => array( 'phone' => $phone )
			));
			if( !empty( $findUserOne ) ){
				return \App\Libs\Views\Json::view(1, '手机号已存在，请输入新手机号', null);		
			}
			//修改
			$user->phone = $phone;//手机号
			$result = $user->save();
			if( !$result ){
				//失败
				return \App\Libs\Views\Json::view(1, '失败', null);
			}
			\App\Libs\Session\Session::resetCache($user);
			$user = $user->toArray();
			$user['type '] = 1;
			$user['age '] = \App\Libs\Helper\CommonHelper::age($user['baby_birthday']);
			$user['vip'] = $user['vip'] == 1?'已开通':'未开通';
			return \App\Libs\Views\Json::view(0, '手机号修改成功', $user);
		}else{
			return \App\Libs\Views\Json::view(Constant::INVALID_CAPTCHA, '验证码无效', null);
		}
		
		
		
	}
}
